<?php

class SmartyDoctrine extends Smarty{
    private static $region;
    private static $debugMode;

    function __construct($baseDir, $lang, $debugging){
        parent::__construct();

        self::$region = $lang;
        self::$debugMode = $this->debugging = $debugging;
        $this->template_dir = 'templates';
        $this->config_dir = 'configs';
        $this->compile_dir = 'templates_c_'.$lang;
        $this->cache_dir = 'cache';

        if (!file_exists($this->compile_dir)){
            @mkdir($this->compile_dir);
        }

        $this->registerPlugin(Smarty::PLUGIN_BLOCK, "t", array($this, 'GetResource'));
        $this->registerFilter(Smarty::FILTER_PRE, array($this, 'PreCompileFilterForLocalization'));
    }

    //region resource

    public function GetResource($params, $content, &$smarty, &$repeat) {
        if(!$repeat){
            if (isset($content)) {
                $language = isset($params['lang']) ? $params['lang'] : appcode\enum\Language::GetDefaultId();
                return $this->FetchFromDb(trim($content), $language);
            }
        }
    }

    /*
     * Translation generation, usage
     * -------------------------------------------------------------
        <h1>/##TTL_WELCOME_HEADING##/</h1>
        <p>/##TXT_WELCOME##/</p>
     * -------------------------------------------------------------
     */
    public function PreCompileFilterForLocalization($template) {
        $region = self::$region;
        $labels = array();

        preg_match_all('~(/##(.*?)##/)~i', $template, $labels);

        foreach ($labels[max(array_keys($labels))] as $label) {
            $t_replace = $this->FetchFromDb($label, $region);
            $template = stripslashes(str_ireplace("/##{$label}##/", $t_replace, $template));
        }

        if(self::$debugMode){
            $debugInfo["region"] = $region;
            $di["PreCompileFilterForLocalization_DEBUG_INFO"][] = $debugInfo;
            echo "<pre>";
            print_r($di);
            echo "</pre>";
        }

        return $template;
    }

    protected function FetchFromDb($label, $region, $arg = "") {
        $label = trim($label);

        $query = Doctrine_Core::getTable('Translation')
            ->createQuery("t")
            ->select("value")
            ->where("visibility_id = ".appcode\enum\Visibility::GetByName(appcode\enum\Visibility::V_public)." and language = '".$region."' and key = '".$label."'");

        $resources = $query->fetchArray();

        $t_replace = "[".$region."][MISSING:".$label."]";
        if(count($resources) != 0){
            $resources = current($resources);
            $t_replace = utf8_decode($resources["value"]);
        }

        return String::Format($t_replace, $arg);
    }

    //endregion resource
}
